using System.Linq;
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Maui.Devices;
using Microsoft.Maui.Storage;
using Microsoft.Maui.Networking;

namespace MauiBuilder.ViewModels
{
    /// <summary>
    /// 设备信息分组模型
    /// </summary>
    public class DeviceInfoGroup : ObservableCollection<DeviceInfoItem>
    {
        public string Name { get; set; }
        
        public DeviceInfoGroup(string name, IEnumerable<DeviceInfoItem> items) : base(items)
        {
            Name = name;
        }
    }

    /// <summary>
    /// 设备信息项模型
    /// </summary>
    public partial class DeviceInfoItem : ObservableObject
    {
        [ObservableProperty]
        private string _icon = string.Empty;

        [ObservableProperty]
        private string _title = string.Empty;

        [ObservableProperty]
        private string _value = string.Empty;

        [ObservableProperty]
        private string _category = string.Empty;
    }

    /// <summary>
    /// 设备信息页面的视图模型
    /// 获取和显示设备的详细信息
    /// </summary>
    public partial class DeviceInfoViewModel : BaseViewModel
    {
        [ObservableProperty]
        private ObservableCollection<DeviceInfoItem> _deviceInfoItems = new();

        [ObservableProperty]
        private ObservableCollection<DeviceInfoGroup> _groupedDeviceInfo = new();

        [ObservableProperty]
        private bool _isRefreshing = false;

        [ObservableProperty]
        private string _lastUpdateTime = string.Empty;

        public DeviceInfoViewModel()
        {
            LoadDeviceInfo();
        }

        /// <summary>
        /// 刷新设备信息命令
        /// </summary>
        [RelayCommand]
        private async Task OnRefreshDeviceInfo()
        {
            IsRefreshing = true;
            try
            {
                await Task.Delay(500); // 模拟刷新延迟
                LoadDeviceInfo();
            }
            finally
            {
                IsRefreshing = false;
            }
        }

        /// <summary>
        /// 复制信息到剪贴板命令
        /// </summary>
        [RelayCommand]
        private async Task OnCopyToClipboard(DeviceInfoItem item)
        {
            try
            {
                
                if (item != null && !string.IsNullOrEmpty(item.Value))
                {
                    var textToCopy = $"{item.Title}: {item.Value}";
                    await Clipboard.Default.SetTextAsync(textToCopy);
                    
                    System.Diagnostics.Debug.WriteLine($"复制成功: {textToCopy}");

                    // 显示成功提示
                    await AppShell.DisplayToastAsync($"✅ 已复制：{item.Title}");
                }
                else
                {
                    await AppShell.DisplayToastAsync("❌ 没有可复制的内容");
                }
            }
            catch (Exception ex)
            {
                await AppShell.DisplayToastAsync($"❌ 复制失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 导出设备信息命令
        /// </summary>
        [RelayCommand]
        private async Task OnExportDeviceInfo()
        {
            try
            {
                var info = GenerateDeviceInfoText();
                await Clipboard.Default.SetTextAsync(info);
                
                // 也可以保存到文件
                // await SaveToFileAsync(info);
            }
            catch (Exception ex)
            {
                // 处理导出错误
                System.Diagnostics.Debug.WriteLine($"导出设备信息失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 加载设备信息
        /// </summary>
        private void LoadDeviceInfo()
        {
            DeviceInfoItems.Clear();

            // 基本设备信息
            AddDeviceInfo("📱", "设备型号", DeviceInfo.Model, "基本信息");
            AddDeviceInfo("🏭", "制造商", DeviceInfo.Manufacturer, "基本信息");
            AddDeviceInfo("📛", "设备名称", DeviceInfo.Name, "基本信息");
            AddDeviceInfo("🔢", "设备版本", DeviceInfo.VersionString, "基本信息");
            AddDeviceInfo("🎯", "设备平台", DeviceInfo.Platform.ToString(), "基本信息");
            AddDeviceInfo("🎨", "设备习语", DeviceInfo.Idiom.ToString(), "基本信息");
            AddDeviceInfo("🔧", "设备类型", DeviceInfo.DeviceType.ToString(), "基本信息");

            // 系统信息
            AddDeviceInfo("💻", "操作系统", $"{DeviceInfo.Platform} {DeviceInfo.VersionString}", "系统信息");
            
            // 屏幕信息
            LoadDisplayInfo();

            // 电池信息
            LoadBatteryInfo();

            // 连接信息
            LoadConnectivityInfo();

            // 存储信息
            LoadStorageInfo();

            // 应用信息
            LoadAppInfo();

            // 创建分组数据
            CreateGroupedData();

            LastUpdateTime = $"最后更新: {DateTime.Now:yyyy-MM-dd HH:mm:ss}";
        }

        /// <summary>
        /// 加载显示信息
        /// </summary>
        private void LoadDisplayInfo()
        {
            try
            {
                var mainDisplay = DeviceDisplay.MainDisplayInfo;
                AddDeviceInfo("📺", "屏幕尺寸", $"{mainDisplay.Width} x {mainDisplay.Height}", "显示信息");
                AddDeviceInfo("🔍", "屏幕密度", $"{mainDisplay.Density:F2}", "显示信息");
                AddDeviceInfo("↕️", "屏幕方向", mainDisplay.Orientation.ToString(), "显示信息");
                AddDeviceInfo("📐", "屏幕刷新率", $"{mainDisplay.RefreshRate:F1} Hz", "显示信息");
            }
            catch (Exception ex)
            {
                AddDeviceInfo("📺", "显示信息", $"获取失败: {ex.Message}", "显示信息");
            }
        }

        /// <summary>
        /// 加载电池信息
        /// </summary>
        private void LoadBatteryInfo()
        {
            try
            {
                var battery = Battery.Default;
                AddDeviceInfo("🔋", "电池电量", $"{battery.ChargeLevel * 100:F0}%", "电池信息");
                AddDeviceInfo("⚡", "电池状态", battery.State.ToString(), "电池信息");
                AddDeviceInfo("🔌", "电源状态", battery.PowerSource.ToString(), "电池信息");
                
                // 省电模式信息（仅在支持的平台上显示）
                try
                {
                    AddDeviceInfo("💡", "省电模式", battery.EnergySaverStatus.ToString(), "电池信息");
                }
                catch
                {
                    // 如果不支持省电模式状态，就忽略
                }
            }
            catch (Exception ex)
            {
                AddDeviceInfo("🔋", "电池信息", $"获取失败: {ex.Message}", "电池信息");
            }
        }

        /// <summary>
        /// 加载连接信息
        /// </summary>
        private void LoadConnectivityInfo()
        {
            try
            {
                var connectivity = Connectivity.Current;
                AddDeviceInfo("🌐", "网络状态", connectivity.NetworkAccess.ToString(), "网络信息");
                
                var profiles = connectivity.ConnectionProfiles;
                if (profiles?.Any() == true)
                {
                    var profileNames = string.Join(", ", profiles.Select(p => p.ToString()));
                    AddDeviceInfo("📡", "连接类型", profileNames, "网络信息");
                }
            }
            catch (Exception ex)
            {
                AddDeviceInfo("🌐", "网络信息", $"获取失败: {ex.Message}", "网络信息");
            }
        }

        /// <summary>
        /// 加载存储信息
        /// </summary>
        private void LoadStorageInfo()
        {
            try
            {
                // 应用数据目录
                AddDeviceInfo("📁", "应用数据目录", FileSystem.AppDataDirectory, "存储信息");
                AddDeviceInfo("💾", "缓存目录", FileSystem.CacheDirectory, "存储信息");
                
                // 获取存储空间信息（如果API支持）
                // 这部分可能需要平台特定的实现
            }
            catch (Exception ex)
            {
                AddDeviceInfo("📁", "存储信息", $"获取失败: {ex.Message}", "存储信息");
            }
        }

        /// <summary>
        /// 加载应用信息
        /// </summary>
        private void LoadAppInfo()
        {
            try
            {
                var appInfo = AppInfo.Current;
                AddDeviceInfo("📦", "应用名称", appInfo.Name, "应用信息");
                AddDeviceInfo("🔢", "应用版本", appInfo.VersionString, "应用信息");
                AddDeviceInfo("🏗️", "构建版本", appInfo.BuildString, "应用信息");
                AddDeviceInfo("📋", "包名", appInfo.PackageName, "应用信息");
                AddDeviceInfo("🎨", "应用主题", appInfo.RequestedTheme.ToString(), "应用信息");
                
                // 应用布局方向
                AddDeviceInfo("🔄", "布局方向", appInfo.RequestedLayoutDirection.ToString(), "应用信息");
            }
            catch (Exception ex)
            {
                AddDeviceInfo("📦", "应用信息", $"获取失败: {ex.Message}", "应用信息");
            }
        }

        /// <summary>
        /// 添加设备信息项
        /// </summary>
        private void AddDeviceInfo(string icon, string title, string value, string category)
        {
            DeviceInfoItems.Add(new DeviceInfoItem
            {
                Icon = icon,
                Title = title,
                Value = value ?? "未知",
                Category = category
            });
        }

        /// <summary>
        /// 创建分组数据
        /// </summary>
        private void CreateGroupedData()
        {
            GroupedDeviceInfo.Clear();
            
            var groups = DeviceInfoItems.GroupBy(x => x.Category).OrderBy(g => g.Key);
            
            foreach (var group in groups)
            {
                GroupedDeviceInfo.Add(new DeviceInfoGroup(group.Key, group));
            }
        }

        /// <summary>
        /// 生成设备信息文本
        /// </summary>
        private string GenerateDeviceInfoText()
        {
            var categories = DeviceInfoItems.GroupBy(x => x.Category).OrderBy(g => g.Key);
            var result = new System.Text.StringBuilder();
            
            result.AppendLine("设备信息报告");
            result.AppendLine($"生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            result.AppendLine();

            foreach (var category in categories)
            {
                result.AppendLine($"【{category.Key}】");
                foreach (var item in category)
                {
                    result.AppendLine($"{item.Title}: {item.Value}");
                }
                result.AppendLine();
            }

            return result.ToString();
        }
    }
}